<template>
  <span 
    class="icon-wrapper" 
    :style="wrapperStyle"
    :class="{ spinning: props.spin }"
  >
    <Icon :icon="iconName" :color="props.color" :width="props.size" :height="props.size" :flip="actualFlip" />
</span>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { Icon } from '@iconify/vue';

interface Props {
  // 图标名称
  name: string
  // 图标大小，可选
  size?: string | number
  // 图标颜色，可选
  color?: string
  // 图标翻转，可选
  flip?: 'h' | 'v' | 'both' | ''
  // 图标旋转，可选
  rotate?: number
  // 图标转动，可选
  spin?: boolean
  // 图标转动速度，可选
  speed?: number
}

const props = withDefaults(defineProps<Props>(), {
  name: '',
  size: '1rem',
  color: 'currentColor',
  flip: '',
  rotate: 0,
  spin: false,
  speed: 1
})

defineOptions({
  name: 'GIcon'
})

const iconName = computed(() => {
  return props.name.includes(':') ? props.name : `mdi:${props.name}`
})

const actualFlip = computed(() => {
  switch (props.flip) {
    case 'h':
      return 'horizontal'
    case 'v':
      return 'vertical'
    case 'both':
      return 'horizontal,vertical'
    default:
      return ''
  }
});

const wrapperStyle = computed(() => {
  const styles: Record<string, string> = {}
  
  if (props.rotate) {
    styles.transform = `rotate(${props.rotate}deg)`
  }
  
  if (props.spin) {
    styles.animationDuration = `${1/props.speed}s`
  }
  
  return styles
})
</script>

<style lang="scss" scoped>
.icon-wrapper {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transform-origin: center center;
  line-height: 0;

  :deep(svg) {
    vertical-align: middle;
  }
}

.spinning {
  animation: spin linear infinite;
  transform-origin: center center;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
